﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Chinesys.Entities.Constants;
using Chinesys.Domain;
using Chinesys.Entities;
using Chinesys.UI.Helpers;
using Chinesys.Domain.InputValidations;
using System.IO;
using Chinesys.Domain.BizRules;

namespace Chinesys.UI.Products
{
    public partial class ProductManagement : PageBase
    {
        public int ProductId
        {
            get
            {
                if (ViewState["ProductId"] == null)
                    return 0;
                else
                    return (int)ViewState["ProductId"];
            }
            set
            {
                ViewState["ProductId"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUserInRole(Constants.Roles.Customer);
            Master.PageTitle = "Administrar Producto";
            ClearMessages();

            if (!IsPostBack)
            {
                LoadLists();
                LoadDropDownList();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool isEdit;
            List<InputValidationError> errors = new List<InputValidationError>();
            ProductEntity product;

            if (this.ProductId != 0)
            {                
                product = ProductDomain.GetByID(this.ProductId);
                product.CurrentState = RowState.Modified;
                isEdit = true;
            }
            else
            {
                product = new ProductEntity();
                product.CurrentState = RowState.New;
                isEdit = false;
            }

            product.Name = TypeHelper.ConvertToType<String>(txtName.Text, "Nombre", errors);
            product.Description = TypeHelper.ConvertToType<String>(txtDecription.Text, "Descripción", errors);
            product.Price = TypeHelper.ConvertToType<Decimal>(txtPriceInDolars.Text, "Precio(us)", errors);
            product.CategoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            product.SubCategoryId = Convert.ToInt32(ddlSubCategory.SelectedValue);

            if (fileUpload.HasFile)
            {
                string newImagePath = SaveImage();

                if (string.IsNullOrEmpty(newImagePath)) //Hubo errores de validación de la imagen subida.
                    return;

                product.ImageSrc = newImagePath;
            }

            if (errors.Any())
            {
                validationSummary.Errors = errors;
            }
            else
            {
                try
                {
                    ProductDomain.Save(product);

                    LoadLists();

                    string action = isEdit ? "Modificado" : "Creado";
                    lblInfo.Text = string.Format("El producto '{0}': ha sido {1} con exito.", product.Name, action);
                    lblInfo.Visible = true;

                    ShowList();
                }
                catch (InputValidationException ex)
                {
                    validationSummary.Errors = ex.Validator.Errors;
                }
                catch (BizRulesException ex)
                {
                    hdnBizRulesException.Value = ex.Message;
                }
            }
        }

        private string SaveImage()
        {
            if (fileUpload.HasFile)
            {
                string relativePath = string.Format(@"/Products/Images/{0}", fileUpload.FileName);
                string absolutePath = Server.MapPath(relativePath);

                if (Path.GetExtension(absolutePath).ToLower() != ".jpg" && Path.GetExtension(absolutePath).ToLower() != ".gif")
                {
                    hdnBizRulesException.Value = "El formato de imagen debe ser .jpg o .gif";
                    return null;
                }

                decimal size = fileUpload.FileBytes.Length / 1024;
                if (size > 1024)
                {
                    hdnBizRulesException.Value = "El tamaño de la imagen no puede superar los 1024Kb (1Mb)";
                    return null;
                }


                byte[] imageBytes = fileUpload.FileBytes;
                FileStream stream = new FileStream(@absolutePath, FileMode.Create);

                stream.Write(imageBytes, 0, imageBytes.Length);
                stream.Close();

                return @relativePath;
            }

            return null;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ShowList();
        }

        private void ShowList()
        {
            pnlEditor.Visible = false;
            pnlList.Visible = true;
        }

        protected void btnNewProduct_Click(object sender, EventArgs e)
        {
            this.ProductId = 0;
            int categoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            LoadSubCategoryDropDownList(categoryId);
            ClearFields();
            ShowEditor();
        }

        private void ClearFields()
        {
            txtName.Text = string.Empty;
            txtDecription.Text = string.Empty;
            txtPriceInDolars.Text = string.Empty;
            imgImage.ImageUrl = string.Empty;
            ddlCategory.SelectedIndex = -1;
            ddlSubCategory.SelectedIndex = -1;
        }

        protected void grdProducts_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "cmdEditProduct")
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    int productID = Convert.ToInt32(((Label)e.Item.FindControl("ID")).Text);
                    LoadProduct(productID);
                }
            }
        }

        private void LoadProduct(int productID)
        {
            this.ProductId = productID;
            ProductEntity prod = ProductDomain.GetByID(productID);
            txtName.Text = prod.Name;
            txtDecription.Text = prod.Description;
            txtPriceInDolars.Text = prod.Price.ToString();
            UIHelper.SelectComboValue(prod.CategoryId.ToString(), ddlCategory);

            LoadSubCategoryDropDownList(prod.CategoryId);

            UIHelper.SelectComboValue(prod.SubCategoryId.ToString(), ddlSubCategory);
            chkActive.Checked = prod.Active;
            imgImage.ImageUrl = prod.ImageSrc;

            ShowEditor();
        }

        private void LoadDropDownList()
        {
            ddlCategory.DataSource = CategoryDomain.GetAll();
            ddlCategory.DataValueField = "Id";
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataBind();
        }

        private void ShowEditor()
        {
            pnlEditor.Visible = true;
            pnlList.Visible = false;
        }

        private void LoadLists()
        {
            grdProducts.DataSource = ProductDomain.GetAll();
            grdProducts.DataBind();
        }
     
        private void ClearMessages()
        {
            lblInfo.Visible = false;
            validationSummary.Clear();
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            int categoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            LoadSubCategoryDropDownList(categoryId);
        }

        private void LoadSubCategoryDropDownList(int categoryId)
        {
            ddlSubCategory.DataSource = SubCategoryDomain.GetByCategory(categoryId);
            ddlSubCategory.DataValueField = "Id";
            ddlSubCategory.DataTextField = "Name";
            ddlSubCategory.DataBind();
        }
    }
}